<template>
  <div class="algorithm-manage custom-el-plus">
    <div class="main-container">
      <div class="base-info item-wrapper">
        <Title titleName="算法基础信息"></Title>
        <div class="base-info-form">
          <el-form
            ref="ruleFormRef"
            :disabled="!editFlag"
            :model="algorithmBaseInfo"
            :rules="formRules"
            inline>
            <el-form-item
              label="算法名称"
              prop="name">
              <el-input v-model="algorithmBaseInfo.name"></el-input>
            </el-form-item>
            <el-form-item
              label="算法编码"
              prop="code">
              <el-input v-model="algorithmBaseInfo.code"></el-input>
            </el-form-item>
            <el-form-item
              label="算法状态"
              prop="startup">
              <el-radio-group v-model="algorithmBaseInfo.startup">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="算法简介"
              prop="profile">
              <el-input v-model="algorithmBaseInfo.profile"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn-group">
          <el-button
            v-if="!editFlag"
            type="primary"
            @click="editBaseInfo"
            >编辑</el-button
          >
          <el-button
            v-if="editFlag"
            @click="cancelBaseInfo"
            >取消</el-button
          >
          <el-button
            v-if="editFlag"
            type="primary"
            @click="saveBaseInfo"
            >保存</el-button
          >
        </div>
      </div>
      <div class="base-info item-wrapper">
        <Title titleName="算法升级"></Title>
        <div class="update-form">
          <el-form
            ref="ruleFormRef"
            :model="upgradeAlgorithmInfo"
            inline>
            <el-form-item>
              <el-upload
                ref="uploadFileRef"
                class="upload-file"
                :limit="1"
                :on-exceed="handleFileExceed"
                :http-request="upgradeAlgorithm"
                :auto-upload="false">
                <template #trigger>
                  <el-button type="primary">
                    <el-icon :size="16"> <Upload /> </el-icon>&nbsp;&nbsp;上传配置文件</el-button
                  >
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="算法描述"
              prop="description">
              <el-input v-model="upgradeAlgorithmInfo.upgradeDesc"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn-group">
          <el-button
            type="primary"
            :loading="upgradeLoadingFlag"
            @click="confirmUpgrade"
            >确定升级</el-button
          >
        </div>
      </div>
      <div class="table-wrapper item-wrapper">
        <Title titleName="关联任务"></Title>
        <div class="table-box">
          <el-table
            :data="dependentTaskTableData"
            style="width: 100%; height: 100%">
            <el-table-column
              label="任务名称"
              prop="taskName"
              width=""></el-table-column>
            <el-table-column
              label="关联设备"
              prop=""
              width=""></el-table-column>
            <el-table-column
              label="设备点位"
              prop=""
              width=""></el-table-column>
            <el-table-column
              label="算法状态"
              prop="startup"
              width="">
              <template #default="{ row }">
                <div :class="row.startup ? 'on-status' : 'off-status'">
                  {{ row.startup ? '启用' : '停用' }}
                </div>
              </template></el-table-column
            >
            <el-table-column
              label="启用时间"
              prop="autoStartTime"
              width=""></el-table-column>
            <el-table-column
              label="停用时间"
              prop="autoEndTime"
              width=""></el-table-column>
            <el-table-column
              label="操作"
              prop=""
              width="">
              <template #default="{ row }">
                <div class="operation-btn-box">
                  <div class="switch-box">
                    <el-switch
                      size="small"
                      v-model="row.isAuto" />
                    <span class="status-label">{{ row.isAuto ? '启用' : '停用' }}</span>
                  </div>
                  <div
                    class="task-detail"
                    @click="toTaskDetail(row.pkId)">
                    转到任务详情
                  </div>
                </div>
              </template></el-table-column
            >
          </el-table>
        </div>
        <!--  <div class="page-box">
          <el-pagination
            style="margin-left: auto"
            :current-page="pageInfo.currentPage"
            :background="true"
            layout="total, prev, pager, next"
            :total="pageInfo.total"
            @current-change="" />
        </div> -->
      </div>
      <div class="table-wrapper item-wrapper">
        <Title titleName="版本管理"></Title>
        <div class="table-box">
          <el-table
            :data="versionManageTableData"
            style="width: 100%; height: 100%">
            <el-table-column
              label="版本序号"
              type="index"
              width="120"></el-table-column>
            <el-table-column
              label="更新时间"
              prop="gmtCreated"
              width=""></el-table-column>
            <el-table-column
              label="更新详情"
              prop="upgradeDesc"
              width=""></el-table-column>
            <el-table-column
              label="操作"
              prop=""
              width=""></el-table-column>
          </el-table>
        </div>
        <!--  <div class="page-box">
          <el-pagination
            style="margin-left: auto"
            :current-page="pageInfo.currentPage"
            :background="true"
            layout="total, prev, pager, next"
            :total="pageInfo.total"
            @current-change="" />
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup>
  import { computed, getCurrentInstance, onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { genFileId } from 'element-plus'
  import { Upload } from '@element-plus/icons-vue'
  import Title from '@/components/title/index.vue'
  import tipMessage from '@/utils/tipMessage'

  const router = useRouter()
  const { proxy } = getCurrentInstance()
  const pageInfo = reactive({
    currentPage: 1,
    pageNum: 1,
    pageSize: 10,
    total: 100
  })
  const algorithmBaseInfo = reactive({
    name: '',
    code: '',
    startup: '',
    profile: ''
  })
  const editFlag = ref(false)
  const formRules = reactive({
    name: [{ required: true, message: '请输入名字', trigger: ['blur'] }],
    startup: [{ required: true, message: '请选择状态', trigger: ['blur'] }]
  })
  const uploadFileRef = ref(null)
  const algorithmDetailInfo = ref({})
  const dependentTaskTableData = computed(() => {
    if (algorithmDetailInfo.value?.taskList?.length) {
      return algorithmDetailInfo.value.taskList
    } else {
      return []
    }
  })
  const versionManageTableData = computed(() => {
    if (algorithmDetailInfo.value?.versionList?.length) {
      return algorithmDetailInfo.value.versionList
    } else {
      return []
    }
  })
  const allAlgorithm = ref([])
  const upgradeAlgorithmInfo = reactive({
    upgradeDesc: ''
  })
  const upgradeLoadingFlag = ref(false)
  /* =======方法======= */
  const editBaseInfo = () => {
    editFlag.value = true
  }

  const saveBaseInfo = async () => {
    try {
      let resData = {
        pkId: algorithmDetailInfo.value.pkId,
        algorithmName: algorithmBaseInfo.name,
        algorithmDesc: algorithmBaseInfo.profile,
        algorithmCode: algorithmBaseInfo.code,
        startup: algorithmBaseInfo.startup
      }
      const res = await proxy.$http.postWithBody('algorithmManage/update', resData)
      if (res === 1) {
        tipMessage('保存成功！', 'success')
        getAlgorithmDetailById(allAlgorithm.value[0]?.pkId)
      } else {
        tipMessage('保存失败！', 'error')
        initAlgorithmBasicInfo()
      }
      editFlag.value = false
    } catch (error) {
      console.log(error)
      tipMessage('保存失败！', 'error')
      initAlgorithmBasicInfo()
    }
  }
  const initAlgorithmBasicInfo = () => {
    algorithmBaseInfo.name = algorithmDetailInfo.value.algorithmName
    algorithmBaseInfo.profile = algorithmDetailInfo.value.algorithmDesc
    algorithmBaseInfo.code = algorithmDetailInfo.value.algorithmCode
    algorithmBaseInfo.startup = algorithmDetailInfo.value.startup
  }
  const cancelBaseInfo = () => {
    editFlag.value = false
    initAlgorithmBasicInfo()
  }
  const handleFileExceed = files => {
    uploadFileRef.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadFileRef.value.handleStart(file)
  }
  const upgradeAlgorithm = async file => {
    upgradeLoadingFlag.value = true
    try {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('algorithmPkId', algorithmDetailInfo.value.pkId)
      formData.append('upgradeDesc', upgradeAlgorithmInfo.upgradeDesc)
      const res = await proxy.$http.postWithBody('algorithmManage/upgrade', formData)
      if (res === 1) {
        tipMessage('更新成功！', 'success')
      } else {
        tipMessage('更新失败！', 'error')
      }
    } catch (error) {
      console.log(error)
      tipMessage('更新失败！', 'error')
    }
    upgradeAlgorithmInfo.upgradeDesc = ''
    upgradeLoadingFlag.value = false
    uploadFileRef.value.clearFiles()
  }
  const confirmUpgrade = () => {
    uploadFileRef.value.submit()
  }
  const toTaskDetail = pkId => {
    router.push({
      name: 'taskManage'
    })
    sessionStorage.setItem('detailTask', pkId)
  }
  const getAllAlgorithm = async () => {
    try {
      let reqData = {
        pageNum: 1,
        pageSize: 10
      }
      const res = await proxy.$http.postWithBody('algorithmManage/selectByCondition', reqData)
      allAlgorithm.value = res
    } catch (error) {
      console.log(error)
    }
  }
  const getAlgorithmDetailById = async pkId => {
    if (pkId) {
      try {
        const res = await proxy.$http.getFun(`algorithmManage/detail/${pkId}`)
        algorithmDetailInfo.value = res
        initAlgorithmBasicInfo()
      } catch (error) {
        console.log(error)
      }
    }
  }
  onMounted(async () => {
    await getAllAlgorithm()
    getAlgorithmDetailById(allAlgorithm.value[0]?.pkId)
  })
</script>

<style scoped lang="scss">
  .algorithm-manage {
    padding: pxTvh(12) pxTvw(24) pxTvh(24) pxTvw(24);
    & > .main-container {
      height: 100%;
      background-color: #0d172f;
      border-radius: pxTvh(4);
      padding: pxTvh(16) pxTvw(16) pxTvh(24) pxTvw(16);
      box-sizing: border-box;
      overflow-y: auto;

      & > .item-wrapper {
        position: relative;
        display: flex;
        flex-direction: column;
        margin-bottom: pxTvh(24);
        & > div:nth-child(2) {
          display: flex;
          width: 100%;
          margin-top: pxTvh(8);
        }
        :deep .el-input {
          width: pxTvw(310);
        }
      }
      & > .base-info {
        & > .base-info-form {
          .el-form {
            width: 100%;
            .el-form-item:last-child {
              flex: 1;
              margin-right: 0;
              .el-input {
                width: 100%;
              }
            }
          }
        }
        & > .update-form {
          .upload-file {
            height: pxTvh(40) !important;
            display: flex;
            align-items: center;
            :deep(.el-upload-list) {
              max-width: pxTvw(150);
              margin-left: pxTvw(12);
              width: fit-content;
              .el-icon:first-child {
                display: none;
              }
              .el-icon {
                color: #cfdbfc;
              }
            }
            :deep(.el-upload-list__item-info) {
              width: fit-content;
            }
            :deep(.el-upload-list__item-file-name) {
              padding-right: pxTvw(24);
              max-width: pxTvw(100);
              color: #cfdbfc;
            }
          }
        }
        & > .btn-group {
          position: absolute;
          top: pxTvh(0);
          right: pxTvw(0);
        }
      }
      & > .table-wrapper {
        flex: 1;
        & > .table-box {
          height: pxTvh(300);
          overflow-y: scroll;
          margin-bottom: pxTvh(16);
          .operation-btn-box {
            @include elasticFN(flex-start, center);
            & > .switch-box {
              height: 100%;
              @include elasticFN(flex-start, center);
              & > .status-label {
                color: #d3dfff;
                height: 100%;
                margin: 0 pxTvw(8);
              }
            }
            & > .task-detail {
              cursor: pointer;
              color: #377dff;
            }
          }
        }
      }
    }
  }
</style>
